package com.ruoyi.student.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import jakarta.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.student.domain.PhdAdmissionInfo;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.domain.StudentInfoImport;
import com.ruoyi.student.service.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.student.domain.StudentBaodao;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 新生报到Controller
 *
 * @author gdslovehy
 * @date 2025-05-22
 */
@RestController
@RequestMapping("/student/baodao")
public class StudentBaodaoController extends BaseController
{
    @Autowired
    private IStudentBaodaoService studentBaodaoService;
    @Autowired
    private IStudentInfoImportService studentInfoImportService;
    @Autowired
    private IStudentInfoService studentInfoService;
    @Autowired
    private StudentImportAsyncService importAsyncService;
    @Autowired
    private IPhdAdmissionInfoService phdAdmissionInfoService;
    @Autowired
    private PhdImportAsyncService phdImportAsyncService;
    /**
     * 查询新生报到列表
     */
//    @PreAuthorize("@ss.hasPermi('student:baodao:list')")
    @GetMapping("/list")
    public TableDataInfo list(StudentBaodao studentBaodao)
    {
        startPage();
        List<StudentBaodao> list = studentBaodaoService.selectStudentBaodaoList(studentBaodao);
        return getDataTable(list);
    }

    /**
     * 导出新生报到列表
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:export')")*/
    @Log(title = "新生报到", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, StudentBaodao studentBaodao)
    {
        List<StudentBaodao> list = studentBaodaoService.selectStudentBaodaoList(studentBaodao);
        ExcelUtil<StudentBaodao> util = new ExcelUtil<StudentBaodao>(StudentBaodao.class);
        util.exportExcel(response, list, "新生报到数据");
    }

    /**
     * 获取新生报到详细信息
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:query')")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(studentBaodaoService.selectStudentBaodaoById(id));
    }

    /**
     * 新增新生报到
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody StudentBaodao studentBaodao)
    {
        studentBaodao.setId(IdUtils.fastSimpleUUID());
        return toAjax(studentBaodaoService.insertStudentBaodao(studentBaodao));
    }

    /**
     * 修改新生报到
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:edit')")*/
    @Log(title = "新生报到", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody StudentBaodao studentBaodao)
    {
        return toAjax(studentBaodaoService.updateStudentBaodao(studentBaodao));
    }

    /**
     * 删除新生报到
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:remove')")*/
    @Log(title = "新生报到", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(studentBaodaoService.deleteStudentBaodaoByIds(ids));
    }

    // 普通新生导入（保留原方法名 insterAll）
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping("/insterAll")
    @Transactional(rollbackFor = Exception.class) // 新增事务，确保删插原子性
    public AjaxResult insterAll() {
        List<StudentInfoImport> studentInfoImportList = studentInfoImportService.selectStudentInfoImportList(new StudentInfoImport());
        List<StudentBaodao> studentBaodaoList = studentBaodaoService.selectStudentBaodaoList(new StudentBaodao());
        int deleteCount = 0;
        int updateCount = 0;
        int insertCount = 0; // 新增：统计“全新添加”的学生数量

        for (StudentInfoImport studentInfoImport : studentInfoImportList) {
            if (Objects.equals(studentInfoImport.getDrzt(), "1")) {
                boolean isExists = false; // 标记：该学生是否已存在报到记录
                String studentNum = studentInfoImport.getXh(); // 当前学生学号

                for (StudentBaodao studentBaodao1 : studentBaodaoList) {
                    // 匹配学号
                    if (Objects.equals(studentNum, studentBaodao1.getStudentNum())) {
                        isExists = true; // 标记为已存在
                        String typeStatus = studentBaodao1.getTypeStatus();

                        // 场景1：已存在 + 状态未通过（0）或空 → 删重导
                        if (Objects.equals(typeStatus, "0") || typeStatus == null) {
                            studentBaodaoService.deleteStudentBaodaoById(studentBaodao1.getId());
                            StudentBaodao studentBaodao = new StudentBaodao();
                            studentBaodao.setId(IdUtils.fastSimpleUUID());
                            studentBaodao.setStudentNum(studentNum);
                            studentBaodao.setStudentName(studentInfoImport.getXm());
                            studentBaodao.setXyCode(studentInfoImport.getLqyxsm());
                            studentBaodao.setStudentXy(studentInfoImport.getXymc());
                            studentBaodao.setStudentZy(studentInfoImport.getLqzymc());
                            studentBaodao.setShuoshiboshi("1");
                            studentBaodao.setTypeStatus("0");
                            studentBaodaoService.insertStudentBaodao(studentBaodao);
                            updateCount++;
                            deleteCount++;
                        }
                        // 场景2：已存在 + 状态已通过（非0）→ 不操作
                        break;
                    }
                }

                // 场景3：遍历完所有已存在记录，仍未匹配 → 全新新增
                if (!isExists && studentNum != null) { // 学号不为空才新增
                    StudentBaodao studentBaodao = new StudentBaodao();
                    studentBaodao.setId(IdUtils.fastSimpleUUID());
                    studentBaodao.setStudentNum(studentNum);
                    studentBaodao.setXyCode(studentInfoImport.getLqyxsm());
                    studentBaodao.setStudentName(studentInfoImport.getXm());
                    studentBaodao.setStudentXy(studentInfoImport.getXymc());
                    studentBaodao.setStudentZy(studentInfoImport.getLqzymc());
                    studentBaodao.setShuoshiboshi("1");
                    studentBaodao.setTypeStatus("0");
                    studentBaodaoService.insertStudentBaodao(studentBaodao);
                    insertCount++;
                }
            }
        }

        // 返回包含“新增数量”的结果
        return AjaxResult.success(String.format("成功导入：更新重导%d条（删除原记录%d条），全新新增%d条",
                        updateCount, deleteCount, insertCount))
                .put("updateCount", updateCount)
                .put("deleteCount", deleteCount)
                .put("insertCount", insertCount);
    }

    // 博士新生导入（保留原方法名 insterAllBoshi）
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping("/insterAllBoshi")
    public AjaxResult insterAllBoshi() {
        System.out.println("===== 开始执行博士新生导入 =====");
        try {
            List<PhdAdmissionInfo> phdAdmissionInfoList = phdAdmissionInfoService.selectPhdAdmissionInfoList(new PhdAdmissionInfo());
            List<StudentBaodao> studentBaodaoList = studentBaodaoService.selectStudentBaodaoList(new StudentBaodao());

            // 打印初始数据量
            System.out.println("从PhdAdmissionInfo表查询到的博士数据总数：" + phdAdmissionInfoList.size());
            System.out.println("当前student_baodao表中已存在的记录数：" + studentBaodaoList.size());

            int successCount = 0; // 原：统计“更新重导”数量
            int failCount = 0;    // 原：统计“已通过跳过”数量
            int insertCount = 0;  // 新增：统计“全新添加”数量

            for (PhdAdmissionInfo phdAdmissionInfo : phdAdmissionInfoList) {
                // 打印当前处理的博士信息
                String currentStudentId = phdAdmissionInfo.getStudentId();
                String currentName = phdAdmissionInfo.getName();
                System.out.println("\n----- 开始处理博士信息：学号=" + currentStudentId + "，姓名=" + currentName + " -----");

                boolean isExists = false; // 标记：该学生是否已存在
                String studentNum = currentStudentId; // 博士学号

                // 检查学号是否为空
                if (studentNum == null) {
                    System.out.println("警告：当前博士信息中学号为空，跳过处理");
                    continue;
                }

                for (StudentBaodao studentBaodao : studentBaodaoList) {
                    if (Objects.equals(studentNum, studentBaodao.getStudentNum())) {
                        isExists = true;
                        String typeStatus = studentBaodao.getTypeStatus();
                        System.out.println("已在student_baodao表中找到该学生，学号=" + studentNum + "，当前状态typeStatus=" + typeStatus);

                        // 场景1：已存在 + 状态未通过（0）或空 → 删重导
                        if (Objects.equals(typeStatus, "0") || typeStatus == null) {
                            System.out.println("执行更新重导：删除原有记录（ID=" + studentBaodao.getId() + "）并重新插入");
                            studentBaodaoService.deleteStudentBaodaoById(studentBaodao.getId());

                            StudentBaodao studentBaodao1 = new StudentBaodao();
                            studentBaodao1.setId(IdUtils.fastSimpleUUID());
                            studentBaodao1.setStudentNum(studentNum);
                            studentBaodao1.setStudentName(phdAdmissionInfo.getName());
                            studentBaodao1.setXyCode(phdAdmissionInfo.getAdmissionCollegeCode());
                            studentBaodao1.setStudentXy(phdAdmissionInfo.getCollegeName());
                            studentBaodao1.setStudentZy(phdAdmissionInfo.getAdmissionMajorName());
                            studentBaodao1.setShuoshiboshi("2");
                            studentBaodao1.setTypeStatus("0");

                            studentBaodaoService.insertStudentBaodao(studentBaodao1);
                            successCount++;
                            System.out.println("更新重导成功，当前successCount=" + successCount);
                        }
                        // 场景2：已存在 + 状态已通过 → 计入failCount（跳过）
                        else {
                            failCount++;
                            System.out.println("状态已通过，跳过处理，当前failCount=" + failCount);
                        }
                        break;
                    }
                }

                // 场景3：不存在 → 全新新增
                if (!isExists) {
                    System.out.println("student_baodao表中不存在该学生，执行全新新增，学号=" + studentNum);
                    StudentBaodao studentBaodao1 = new StudentBaodao();
                    studentBaodao1.setId(IdUtils.fastSimpleUUID());
                    studentBaodao1.setStudentNum(studentNum);
                    studentBaodao1.setStudentName(phdAdmissionInfo.getName());
                    studentBaodao1.setXyCode(phdAdmissionInfo.getAdmissionCollegeCode());
                    studentBaodao1.setStudentXy(phdAdmissionInfo.getCollegeName());
                    studentBaodao1.setStudentZy(phdAdmissionInfo.getAdmissionMajorName());
                    studentBaodao1.setShuoshiboshi("2");
                    studentBaodao1.setTypeStatus("0");

                    studentBaodaoService.insertStudentBaodao(studentBaodao1);
                    insertCount++;
                    System.out.println("全新新增成功，当前insertCount=" + insertCount);
                }
            }

            // 打印最终统计结果
            int totalSuccess = successCount + insertCount;
            System.out.println("\n===== 博士新生导入处理完毕 =====");
            System.out.println("统计结果：更新重导=" + successCount + "条，全新新增=" + insertCount + "条，跳过=" + failCount + "条，总计成功=" + totalSuccess + "条");

            return AjaxResult.success(String.format("成功导入：更新重导%d条，全新新增%d条，因已通过跳过%d条，总计成功%d条",
                            successCount, insertCount, failCount, totalSuccess))
                    .put("updateCount", successCount)
                    .put("insertCount", insertCount)
                    .put("skipCount", failCount)
                    .put("totalSuccess", totalSuccess);
        } catch (Exception e) {
            // 捕获并打印异常信息
            System.err.println("\n===== 博士新生导入发生异常，事务将回滚 =====");
            e.printStackTrace(); // 打印完整异常堆栈
            throw e; // 继续抛出异常，确保事务回滚
        }
    }

    /**
     * 启动异步导入学生数据
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping("/startImport")
    public AjaxResult startImport() {
        String batchNo = IdUtils.fastUUID(); // 生成唯一批次号
        importAsyncService.doImport(batchNo); // 启动异步任务
        return AjaxResult.success("导入已启动，请等待处理", batchNo);
    }

    /**
     * 查询导入进度
     */
    @GetMapping("/importProgress/{batchNo}")
    public AjaxResult getImportProgress(@PathVariable String batchNo) {
        StudentImportAsyncService.ImportProgress progress = importAsyncService.getImportProgress(batchNo);
        return AjaxResult.success(progress);
    }
    /**
     * 启动博士数据导入任务
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping("/startBoShiImport")
    public AjaxResult startBoShiImport() {
        String batchNo = IdUtils.fastUUID(); // 生成唯一批次号
        phdImportAsyncService.doImport(batchNo); // 启动异步导入任务
        return AjaxResult.success("博士数据导入已启动，请等待处理", batchNo);
    }
    /**
     * 查询博士数据导入进度
     */

    @GetMapping("/importBoShiProgress/{batchNo}")
    public AjaxResult getImportBoShiProgress(@PathVariable String batchNo) {
        PhdImportAsyncService.ImportProgress progress = phdImportAsyncService.getImportProgress(batchNo);
        System.out.println(progress);
        return AjaxResult.success(progress);
    }
    /**
     * 原有同步导入方法（保留但不推荐使用）
     */
/*    @PreAuthorize("@ss.hasPermi('student:baodao:add')")*/
    @Log(title = "新生报到", businessType = BusinessType.INSERT)
    @PostMapping("/instertostudent")
    public AjaxResult importData(){
        List<StudentInfo> studentInfoList = studentInfoService.selectStudentInfoList(new StudentInfo());
        int count = 0;
        List<StudentBaodao> studentBaodaoList = studentBaodaoService.selectStudentBaodaoList(new StudentBaodao());

        for (StudentBaodao studentBaodao : studentBaodaoList) {
            boolean flag = false;
            for (StudentInfo studentInfo : studentInfoList) {
                if (studentInfo.getStudentId()!= null && studentInfo.getStudentId().equals(studentBaodao.getStudentNum())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                StudentInfo studentInfoDemo = new StudentInfo();
                StudentInfoImport studentInfoImport = new StudentInfoImport();
                studentInfoImport.setXh(studentBaodao.getStudentNum());
                List<StudentInfoImport> studentInfoImportList = studentInfoImportService.selectStudentInfoImportList(studentInfoImport);
                if (studentInfoImportList.size() != 1) {
                    return AjaxResult.error("导入失败，请检查学号是否正确,查询到该学号下有多位学生数据");
                }
                studentInfoDemo.setId(IdUtils.fastSimpleUUID());
                studentInfoDemo.setStudentId(studentInfoImportList.get(0).getXh());
                studentInfoDemo.setStudentName(studentInfoImportList.get(0).getXm());
                studentInfoDemo.setStudentZy(studentInfoImportList.get(0).getLqzydm());
                studentInfoDemo.setStudentYx(studentInfoImportList.get(0).getLqyxsm());
                studentInfoDemo.setStudentRegion("中华人民共和国");
                studentInfoDemo.setStudentHk(studentInfoImportList.get(0).getHkszdm());
                studentInfoDemo.setStudentHkxxdz(studentInfoImportList.get(0).getHkszdxxdz());
                studentInfoDemo.setStudentSex(studentInfoImportList.get(0).getXbm());
                studentInfoDemo.setStudentXz(studentInfoImportList.get(0).getXz());

                // 安全处理学号截取
                String xh = studentInfoImportList.get(0).getXh();
                if (xh != null && xh.length() >= 9) {
                    studentInfoDemo.setStudentNj(xh.substring(5, 9));
                } else {
                    studentInfoDemo.setStudentNj("");
                }

                studentInfoDemo.setStudentBydw(studentInfoImportList.get(0).getBydw());
                studentInfoDemo.setStudentByzy(studentInfoImportList.get(0).getByzymc());
                studentInfoDemo.setStudentByzym(studentInfoImportList.get(0).getByzydm());
                studentInfoDemo.setStudentYjfxm(studentInfoImportList.get(0).getLqyjfxdm());
                studentInfoDemo.setStudentYjfx(studentInfoImportList.get(0).getLqyjfxmc());
                studentInfoDemo.setStudentNation(studentInfoImportList.get(0).getMzm());
                studentInfoDemo.setStudentCtype(studentInfoImportList.get(0).getZjlx());
                studentInfoDemo.setStudentCnum(studentInfoImportList.get(0).getZjhm());
                studentInfoDemo.setBirthday(studentInfoImportList.get(0).getCsrq());
                studentInfoDemo.setStudentPa(studentInfoImportList.get(0).getZzmmm());
                studentInfoDemo.setStudentMarr(studentInfoImportList.get(0).getHfm());
                studentInfoDemo.setStudentSjby(studentInfoImportList.get(0).getByny());
                studentInfoDemo.setStudentZxjh(studentInfoImportList.get(0).getZxjh());
                studentInfoDemo.setStudentXxfs(studentInfoImportList.get(0).getLqxxfs());
                studentInfoDemo.setStudentDadz(studentInfoImportList.get(0).getDaszdwdz());
                studentInfoDemo.setStudentDadzyzbm(studentInfoImportList.get(0).getDaszdwyzbm());
                studentInfoDemo.setStudentXwzh(studentInfoImportList.get(0).getXwzsbh());
                studentInfoDemo.setKsfs(studentInfoImportList.get(0).getKsfsm());
                studentInfoDemo.setBeizhu(studentInfoImportList.get(0).getBz());
                studentInfoDemo.setStudentDxjydw(studentInfoImportList.get(0).getDxwpdw());
                studentInfoDemo.setStudentLqpydw(studentInfoImportList.get(0).getLhpydw());
                studentInfoDemo.setStudentLqpydwm(studentInfoImportList.get(0).getLhpydwm());
                studentInfoDemo.setStudentSjh(studentInfoImportList.get(0).getLxfs());
                studentInfoDemo.setStudentRwsj(studentInfoImportList.get(0).getRwny());
                studentInfoDemo.setStudentTysj(studentInfoImportList.get(0).getTyny());
                studentInfoDemo.setStudentPzrujgmc(studentInfoImportList.get(0).getRwpzdw());
                studentInfoDemo.setStudentPztyjgmc(studentInfoImportList.get(0).getTypzdw());
                studentInfoDemo.setStudentTcxyzbh(studentInfoImportList.get(0).getTcxyzbh());
                studentInfoDemo.setStudentRwqszgxmc(studentInfoImportList.get(0).getRwqgxmc());
                studentInfoDemo.setStudentRwqszgxxxxs(studentInfoImportList.get(0).getRwqxxxs());
                studentInfoDemo.setStudentRwqszgxxxzy(studentInfoImportList.get(0).getRwqzymc());


                studentInfoService.insertStudentInfo(studentInfoDemo);
                count++;
            }
        }

        return AjaxResult.success("成功导入",count);
    }
}
